package org.oims.simpleserver.endpoint;

import org.oims.simpleserver.exceptions.ClientOfflineException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class EndpointArbiter {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    private EndpointPool endpointPool;

    public void register(String id, Endpoint endpoint){
        endpointPool.put(id, endpoint);
        logger.info("Register endpoint successfully, id: '" + id + "', hash code: '" + endpoint.hashCode() + "'");
    }

    public void unregister(String id){
        endpointPool.remove(id, null);
    }

    public void unregister(String id, Endpoint endpoint){
        endpointPool.remove(id, endpoint);
    }

    public void pushMsg(String id, String msg) throws ClientOfflineException, IOException {
        Endpoint endpoint = endpointPool.get(id);
        if(endpoint == null){
            throw new ClientOfflineException(id);
        }
        endpoint.sendMsg(msg);
    }

    @Autowired
    public void setEndpointPool(EndpointPool endpointPool) {
        this.endpointPool = endpointPool;
    }
}
